<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>easyconfig用户管理</title>
        <script src="./lib/axios.js"></script>
        <script src="./lib/vue.js"></script>
        <link rel="stylesheet" href="./lib/elementindex.css">
        <script src="./lib/elementindex.js"></script>
    </head>
    <body>
        <div id='admins'>
            <el-card style="font-size:small;margin-bottom: 1.125rem;">
                <el-link href="./home.html" style="color: blue;">&lt;&lt;&lt;返回配参查看编辑页面</el-link>
            </el-card>
            <el-row>
                <el-col :span='16'>&nbsp;</el-col>
                <el-col :span='8'>
                    <el-button size='mini' type="primary" @click="handleCreate()">
                        新建用户
                    </el-button>
                </el-col>
            </el-row>

            <el-table border :data="userList" style="width: 100%;" row-key="username">
                <el-table-column label="账户名称" prop="username">
                </el-table-column>

                <el-table-column label="备注信息" prop="remarks">
                </el-table-column>

                <el-table-column label="权限" prop="admin">
                    <template slot-scope="scope">
                        <el-tag size='mini' v-if="(scope.row.func & 1) != 0">查看</el-tag>
                        <el-tag size='mini' v-if="(scope.row.func & 2) != 0">修改</el-tag>
                        <el-tag size='mini' v-if="(scope.row.func & 4) != 0">发布</el-tag>
                        <el-tag size='mini' v-if="(scope.row.func & 8) != 0">安全</el-tag>
                        <el-tag size='mini' v-if="(scope.row.func & 16) != 0">数据</el-tag>
                    </template>
                </el-table-column>

                <el-table-column title="操作" width="240px">
                    <template slot="header">
                        <span>操作</span>
                    </template>
                    <template slot-scope="scope">
                        <el-button size='mini' type="primary" @click="handleUserAuth(scope.row)">
                            授权
                        </el-button>
                        <el-button size='mini' type="primary" @click="handleUserPassword(scope.row)">
                            密码
                        </el-button>
                        <el-button size='mini' type="primary" @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>


        </div>
        <script type="module" id="admins-script">
            window.hosturl = document && document.location.href.startsWith('http://127.0.0.1:8848') ? 'http://localhost/resources' : '.';
            
            window.vmadmins = new Vue({
               el: '#admins',
               data: {
                    userList:[],
               },
               methods: {
                   handleDelete(user){
                       deleteUser(user);
                   },
                   handleUserAuth(user)
                   {
                       window.vmauths.showform(user,(u)=>{
                           if(JSON.stringify(user) == JSON.stringify(u)) return;
                           user.acl = u.acl;
                           user.func = u.func;
                           user.remarks = u.remarks;
                           window.handleUserPut(user);
                       });
                   },
                   handleUserPassword(user)
                   {
                       window.vmPaswordChangeDlg.showform(user,(u)=>{
                           if(JSON.stringify(user) == JSON.stringify(u)) return;
                           user.password = u.password;
                           user.remarks = u.remarks;
                           window.handleUserPut(user);
                       });
                   },
                   handleCreate()
                   {
                       vmUserDlg.showUserDlg=true;
                   }
               },//end of method
               computed:{
        
               },
           });
           
         window.loadData = function()
         {
             axios.get(window.hosturl +'/security-user-list').then(resp=>{
                 // console.warn("loadData()",resp);
                 if(resp.data.error || typeof resp.data!=='object')
                 {
                     window.vmadmins.$message({showClose:true,type:'error',message:resp.data.data});
                     return;
                 }
                 
                 vmadmins.userList = resp.data.data;
             }).catch(ex=>{
                 vmadmins.$message({showClose:true,type:"error",message:ex});
             });
         }
         
         window.loadData();
         
         window.createUser=function(user)
         {
             axios.post(window.hosturl +'/security-user-create',user).then(resp=>{
                 vmadmins.userList = resp.data.data;
             }).catch(ex=>{
                 vmadmins.$message({showClose:true,type:"error",message:ex});
             });
         }
         
         window.handleUserPut=function(user)
         {
             axios.post(window.hosturl +'/security-user-put',user).then(resp=>{
                 vmadmins.userList = resp.data.data;
             }).catch(ex=>{
                 vmadmins.$message({showClose:true,type:"error",message:ex});
             });
         }
         
         window.deleteUser=function(user)
         {
             vmadmins.$confirm(`删除用户操作会立即执行生效, 是否继续?`, '提示', {
                 cancelButtonText: '取消',
                 confirmButtonText: '确定',
                 type: 'warning',
                 center: true
             }).then(doDelete).catch(action=>{console.log(action);});
             
             function doDelete()
             {
                 axios.post(window.hosturl +'/security-user-delete',user).then(resp=>{
                     vmadmins.userList = resp.data.data;
                 }).catch(ex=>{
                     vmadmins.$message({showClose:true,type:"error",message:ex});
                 });
             }
         }
        </script>

        <div id='paswordChangeDlg'>
            <el-dialog :visible.sync="showPaswordChangeDlg" title="重置用户密码">
                <el-form label-width="100px" :model="user" ref="showPaswordChangeDlg">
                    <el-form-item id='username-userDlg' size='small' label="账户名称" prop="username">
                        <el-input type="textarea" :disabled="true" v-model="user.username" rows="1">
                        </el-input>
                    </el-form-item>

                    <el-form-item id='password-paswordChangeDlg' size='small' label="访问密码" prop="password" :rules="[
                    { required: true, message: '用户密码,区分大小写.', trigger: 'blur' },
                    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }]">
                        <el-input type="password" v-model="user.password" placeholder="用户密码,区分大小写." rows="1">
                        </el-input>
                    </el-form-item>

                    <el-form-item id='password-confirm-paswordChangeDlg' size='small' label="密码确认" prop="confirm" :rules="[
                    { required: true, message: '请重新录入用户密码,以防止手误.', trigger: 'blur' },
                    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' },
                    {validator:handleValueValidate,trigger:'blur'}]">
                        <el-input type="password" v-model="user.confirm" placeholder="请重新录入用户密码,以防止手误." rows="1">
                        </el-input>
                    </el-form-item>

                    <el-form-item id='remarks-paswordChangeDlg' size='small' label="备注信息" prop="remarks" :rules="[
                       { min: 0, max: 64, message: '长度在 0 到 64 个字符', trigger: 'blur' },
                    ]">
                        <el-input type="textarea" v-model="user.remarks" placeholder="可选的用户备注信息." rows="1">
                        </el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button @click='handlePasswordChanged' type="primary">确 认</el-button>
                        <el-button @click='showPaswordChangeDlg=false'>取 消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>

        <script type="module" id="paswordChangeDlg-script">
            window.vmPaswordChangeDlg = new Vue({
               el: '#paswordChangeDlg',
               data: {
                    showPaswordChangeDlg:false,
                    user:{username:'',password:'',confirm:'',remarks:''},
               },
               methods: {
                   showform:function(user,callback)
                   {
                       console.log('showform:function(user,callback)',user);
                       this.user = user?JSON.parse(JSON.stringify(user)):{};
                       this.callback = callback;
                       this.showPaswordChangeDlg = true;
                   },
                   handleValueValidate(rule,value,callback)
                   {
                       if(rule.field ==='confirm')
                       {
                           if(this.user.password !== this.user.confirm)
                           {
                               callback(new Error('两次输入的用户密码不一致。'))
                           }
                       }
                       callback();
                   },
                  handlePasswordChanged()
                  {
                      let self = this;
                      this.$refs['showPaswordChangeDlg'].validate((valid) => {
                                if (valid) {
                                   doHandlePasswordChanged();
                                } else {
                                  return false;
                                }
                              });
                       
                       function doHandlePasswordChanged(){
                           if(self.callback)self.callback(self.user)
                           self.showPaswordChangeDlg = false;
                       }
                  }
               },//end of method
              
           });
        </script>
        
        <div id='userDlg'>
            <el-dialog :visible.sync="showUserDlg" title="创建新用户">
                <el-form label-width="100px" :model="user" ref="showUserDlgForm">
                    <el-form-item id='username-userDlg' size='small' label="账户名称" prop="username" :rules="[
                    { required: true, message: '请输入用户在系统的名称,建议为手机号码或email.', trigger: 'blur' },
                    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' },
                    {validator:handleValueValidate,trigger:'blur'}]">
                        <el-input type="textarea" v-model="user.username" placeholder="用户在系统的名称,建议为手机号码或email." rows="1">
                        </el-input>
                    </el-form-item>

                    <el-form-item id='password-userDlg' size='small' label="访问密码" prop="password" :rules="[
                    { required: true, message: '用户密码,区分大小写.', trigger: 'blur' },
                    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }]">
                        <el-input type="password" v-model="user.password" placeholder="用户密码,区分大小写." rows="1">
                        </el-input>
                    </el-form-item>

                    <el-form-item id='password-confirm-userDlg' size='small' label="密码确认" prop="confirm" :rules="[
                    { required: true, message: '请重新录入用户密码,以防止手误.', trigger: 'blur' },
                    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' },
                    {validator:handleValueValidate,trigger:'blur'}]">
                        <el-input type="password" v-model="user.confirm" placeholder="请重新录入用户密码,以防止手误." rows="1">
                        </el-input>
                    </el-form-item>

                    <el-form-item id='remarks-userDlg' size='small' label="备注信息" prop="remarks" :rules="[
                       { min: 0, max: 64, message: '长度在 0 到 64 个字符', trigger: 'blur' },
                    ]">
                        <el-input type="textarea" v-model="user.remarks" placeholder="可选的用户备注信息." rows="1">
                        </el-input>
                    </el-form-item>

                    <span v-if="inlineErrorMessage" style="color: red;">{{inlineErrorMessage}}</span>

                    <el-form-item>
                        <el-button @click='handleUserCreated' type="primary">确 认</el-button>
                        <el-button @click='showUserDlg=false'>取 消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>

        <script type="module" id="userDlg-script">
            window.vmUserDlg = new Vue({
               el: '#userDlg',
               data: {
                    showUserDlg:false,
                    user:{username:'',password:'',remarks:''},
                    inlineErrorMessage:"",
               },
               methods: {
                   handleValueValidate(rule,value,callback)
                   {
                       if(rule.field ==='username')
                       {
                           let u = window.vmadmins.userList.find(it=>it.username === value);
                           if(u)
                           {
                               callback(new Error('用于已经存在。'))
                           }
                       }else if(rule.field ==='confirm')
                       {
                           if(this.user.password !== this.user.confirm)
                           {
                               callback(new Error('两次输入的用户密码不一致。'))
                           }
                       }
                       //backend
                       callback();
                   },
                  handleUserCreated()
                  {
                      let self = this;
                      this.$refs['showUserDlgForm'].validate((valid) => {
                                if (valid) {
                                   doHandleUserCreated();
                                } else {
                                  return false;
                                }
                              });
                       
                       function doHandleUserCreated(){
                           
                           self.showUserDlg = false;
                           window.createUser(self.user);
                       }
                  }
               },//end of method
              
           });
        </script>


        <div id='auths' style="display: none;">
            <el-dialog width='70%' :visible.sync="showAuthsForm" :title="'为['+user.username+']用户授权'">
                <el-form ref="authsForm" :model='mockmodel' label-width="80px">
                    <el-form-item label="用户备注:">
                        <el-input type='textarea' rows='1' v-model.trim="user.remarks">
                        </el-input>
                    </el-form-item>
                    
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>功能权限</span>
                            &nbsp;&nbsp;&nbsp;
                            <el-checkbox :value="(user.func & 15) === 15" @change="handleCheckFunc(15,$event)">全部
                            </el-checkbox>
                        </div>
                        <div class="text item">
                            <el-checkbox :value="(user.func & 1) === 1" @change="handleCheckFunc(1,$event)">
                                <el-tooltip content="Bottom center" placement="bottom" effect="light">
                                    <span>查看配置项</span>
                                    <div slot="content">
                                        <span>查看配参数据项，获得当前系统的配参数值</span>
                                    </div>
                                </el-tooltip>
                            </el-checkbox>
                            <el-checkbox :value="(user.func & 2) === 2" @change="handleCheckFunc(2,$event)">
                                <el-tooltip content="Bottom center" placement="bottom" effect="light">
                                    <span>修改配置项</span>
                                    <div slot="content">
                                        <span>提交配参数据项的修改(不包括发布生效)</span>
                                    </div>
                                </el-tooltip>
                            </el-checkbox>
                            <el-checkbox :value="(user.func & 4) === 4" @change="handleCheckFunc(4,$event)">
                                <el-tooltip content="Bottom center" placement="bottom" effect="light">
                                    <span>发布配置项</span>
                                    <div slot="content">
                                        <span>用修改后的配参数据项数值，更新系统中运行对象，让系统以新的配参行为运行</span>
                                    </div>
                                </el-tooltip>
                            </el-checkbox>
                            <el-checkbox :value="(user.func & 8) === 8" @change="handleCheckFunc(8,$event)">
                                <el-tooltip content="Bottom center" placement="bottom" effect="light">
                                    <span>管理用户安全</span>
                                    <div slot="content">
                                        <span>新建、删除easyconfig用户，调整用户的安全授权</span>
                                    </div>
                                </el-tooltip>
                            </el-checkbox>
                        </div>
                    </el-card>

                    <br />

                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>数据权限</span>
                            &nbsp;&nbsp;&nbsp;
                            <el-checkbox :value="(user.func & 16) === 16" @change="handleCheckFunc(16,$event)">
                                <el-tooltip content="Bottom center" placement="bottom" effect="light">
                                    <span>启动数据权限</span>
                                    <div slot="content">
                                        <li>细粒度的权限控制，不同配参数据项单独控制权限</li>
                                    </div>
                                </el-tooltip>
                            </el-checkbox>
                        </div>
                        <div class="text item">
                            <el-table v-if="(user.func & 16) != 0" border ref='useracl' :data="user.acl" style="width: 100%;"
                                max-height="400px" row-key="id">
                                <el-table-column label="配置代码前缀" prop="i">
                                    <template slot="header">
                                        <el-tooltip content="Bottom center" placement="bottom" effect="light">
                                            <span>配置代码前缀<i class="el-icon-question"></i></span>
                                            <div slot="content">
                                                <li>*代表任意配置项</li>
                                                <li>abc*代表任意以abc开头的配置项</li>
                                                <li>abc.def只代表配置项abc.def自身</li>
                                            </div>
                                        </el-tooltip>
                                    </template>
                                    <template slot-scope="scope">
                                        <el-form-item :rules="{validator:(x,y,z)=>handleValueValidate(x,y,z,scope.row),trigger:'blur'}"
                                            :prop="'i'" style='width: 100%;'>
                                            <el-input v-if="editing === scope.row.id" style='width: 100%;' type="textarea"
                                                rows="1" v-model.trim="scope.row.i" placeholder="权限控制的配置项前缀(*代表全部)">
                                            </el-input>
                                            <span v-else>{{scope.row.i}}</span>
                                        </el-form-item>

                                    </template>
                                </el-table-column>
                                <el-table-column label="权限" width='360px'>
                                    <template slot-scope="scope">
                                        <el-row>
                                            <el-col :span='8'>
                                                <el-checkbox :key="'all-'+scope.row.id" :value="(scope.row.a & 7) === 7"
                                                    @change="handleCheckAuths(scope.row,7,$event)">全部
                                                </el-checkbox>
                                            </el-col>
                                            <el-col :span='16'>
                                                <el-checkbox :key="'v-'+scope.row.id" :value="(scope.row.a & 1) !== 0"
                                                    @change="handleCheckAuths(scope.row,1,$event)">查看
                                                </el-checkbox>
                                                <el-checkbox :key="'p-'+scope.row.id" :value="(scope.row.a & 2) !== 0"
                                                    @change="handleCheckAuths(scope.row,2,$event)">修改
                                                </el-checkbox>
                                                <el-checkbox :key="'d-'+scope.row.id" :value="(scope.row.a & 4) !== 0"
                                                    @change="handleCheckAuths(scope.row,4,$event)">发布
                                                </el-checkbox>
                                            </el-col>
                                        </el-row>
                                    </template>
                                </el-table-column>

                                <el-table-column title="操作" width='280px'>
                                    <template slot="header"><span>操作</span>
                                        <el-button type="success" size='mini' @click="handleAclAppend">
                                            创建
                                        </el-button>
                                    </template>
                                    <template slot-scope="scope">
                                        <el-button size='mini' @click="triggerAclEdit(scope.row)">
                                            <span v-if="editing === scope.row.id">展示</span><span v-else>编辑</span>
                                        </el-button>
                                        <el-button size='mini' @click="handleAclDelete(scope.row)">
                                            删除
                                        </el-button>
                                        <el-button size="mini" type="text" icon="el-icon-bottom icon_class" @click="moveDown(scope.$index,scope.row)">
                                            下移
                                        </el-button>
                                        <el-button size="mini" type="text" icon="el-icon-top icon_class" @click="moveUp(scope.$index,scope.row)">
                                            上移
                                        </el-button>

                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-card>
                    <br />
                    <el-form-item>
                        <el-row>
                            <el-col :span="8">&nbsp;</el-col>
                            <el-col :span="8">
                                <el-button @click='handleAuthsSubmit' type="primary">确 认</el-button>
                                <el-button @click='showAuthsForm=false'>取 消</el-button>
                            </el-col>
                            <el-col :span="8">&nbsp;</el-col>
                        </el-row>

                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
        <script type="module" id="auths-script">
            window.vmauths = new Vue({
               el: '#auths',
               data: {
                   showAuthsForm:false,
                   editing:null,
                   maxid:0,
                   user:{},
                   mockmodel:{},
               },
               mounted:function()
               {
                   this.$el.style.display= 'block';
               },
               methods: {
                   moveUp(index, row) {
                     var that = this
                     if (index > 0) {
                       const upDate = that.user.acl[index - 1]
                       that.user.acl.splice(index - 1, 1)
                       that.user.acl.splice(index, 0, upDate)
                       this.$refs.useracl.setCurrentRow(row);
                     } else {
                       that.$message({showClose:true,type:"warning",message:'已经是第一条，不可上移'});
                     }
                   },
                   moveDown(index, row) {
                     var that = this
                     if ((index + 1) === that.user.acl.length) {
                       that.$message({showClose:true,type:"warning",message:'已经是最后一条，不可下移'});
                     } else {
                       const downDate = that.user.acl[index + 1]
                       that.user.acl.splice(index + 1, 1)
                       that.user.acl.splice(index, 0, downDate)
                       this.$refs.useracl.setCurrentRow(row);
                     }
                   },
                   showform:function(user,callback)
                   {
                       console.log('showform:function(user,callback)',user);
                       this.user = user?JSON.parse(JSON.stringify(user)):{};
                       let maxid = 0
                       if(this.user.acl==null)this.user.acl=[];
                       this.user.acl.forEach(it=>it.id = ++maxid);
                       this.maxid = maxid;
                       this.callback = callback;
                       this.showAuthsForm = true;
                   },
                   handleCheckFunc:function(mask, $evt)
                   {
                       if($evt) this.user.func = this.user.func | mask;
                       else this.user.func = this.user.func & ~mask;
                   },
                   handleCheckAuths:function(row,act,$evt)
                   {
                       console.log('row,act,$evt',row,act,$evt,)
                       row.a = $evt ? (row.a | act) : (row.a & (~act));
                   },
                   triggerAclEdit:function(row)
                   {
                       let self = this;
                       if(!this.editing)
                       {
                           this.editing = row.id;
                       } else{
                           this.$refs['authsForm'].validate((valid) => {
                                     if (valid) self.editing = 0 ; else return false;
                                });
                       }
                   },
                   handleAuthsSubmit:function()
                   {
                     if(this.callback)this.callback(this.user)
                     this.showAuthsForm =false;
                   },
                   
                   handleAclAppend:function()
                   {
                       let self = this;
                       this.$refs['authsForm'].validate((valid) => {
                                 if (valid) doAction(); else return false;
                               });
                        
                        function doAction(){
                           let group = {id: ++self.maxid,i:'*',a:0};
                           self.user.acl.splice(self.user.acl.length,0,group);
                           self.editing = group.id;
                        }
                   },
                   handleAclDelete:function(row)
                   {
                       let index = this.user.acl.findIndex(it=>it.id===row.id);
                       this.user.acl.splice(index,1); 
                   },
                   handleValueValidate:function(rule,value,callback,row)
                   {
                       let val = row[rule.field];
                       if(!val){ 
                           callback(new Error('不能为空'));
                        };
                        
                        callback();
                   },
               },//end of method
           });
                   
        </script>
        <div id='bottom'></div>
    </body>
</html>
